import { EllipsisOutlined, ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import { Avatar, Button, Col, DatePicker, Dropdown, Flex, message, Modal, Progress, Row, Space, Tag } from 'antd';
import { useEffect, useRef, useState } from 'react';
import request from 'umi-request';
import AddInterview from './AddInterview';
import DetailsInterview from './DetailInterview';
import { Pie } from '@ant-design/plots';
import { deleteInterview, getStatisticsRecord, pageInterview } from '@/services/api/api-interview-record';
import { useAccess } from '@umijs/max';
import { parse } from '@/utils/historyUtils';
import { mediaList } from '@/services/api/api-monitor-linkage';

interface TabableInterviewProps {
    type: number
}

const TableInterview: React.FC<TabableInterviewProps> = ({ type }) => {
    const actionRef = useRef<ActionType>();
    const access = useAccess();
    const [interviewId, setInterviewId] = useState<string>()
    const columns: ProColumns<InterviewRecordData.PageVo>[] = [
        {
            title: '活动主题',
            dataIndex: 'name',
            copyable: true,
            ellipsis: true,
            tooltip: '名称过长会自动收缩',
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '此项为必填项',
                    },
                ],
            },
            render: (dom, record, _index, action) => {
                return <>
                    <Tag color={record.status === 0 ? 'error' : 'success'}>{record.status === 0 ? '已结束' : '进行中'}</Tag>
                    <DetailsInterview id={record.id} title={String(record.title)} onRefurbish={handleReload} interviewId={String(interviewId)} />
                </>
            },
        },
        {
            disable: true,
            title: '状态',
            dataIndex: 'interviewState',
            hideInTable: true,
            valueType: 'select',
            filters: true,
            onFilter: true,
            ellipsis: true,
            valueEnum: {
                0: {
                    text: '已结束',
                },
                1: {
                    text: '进行中',
                },
            },
        },
        {
            title: '采访媒体',
            dataIndex: 'mediaNames',
            hideInSearch: true,
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '此项为必填项',
                    },
                ],
            },
            render: (dom, record, _index, action) => {
                let mediaNames = record?.mediaNames;

                if (mediaNames.length > 2) {
                    mediaNames = mediaNames.slice(0, 2);
                    mediaNames.push("...");
                }
                return <Space wrap size="small">
                    {mediaNames.map((item) => {
                        return <Tag key={item}> {item}</Tag>;
                    })}
                </Space>

            },
        },
        {
            title: '采访对象',
            dataIndex: 'assignOrganizationNames',
            hideInSearch: true,
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '此项为必填项',
                    },
                ],
            },
            render: (dom, record, _index, action) => {
                let assignOrganizationNames = record?.assignOrganizationNames;

                if (assignOrganizationNames.length > 2) {
                    assignOrganizationNames = assignOrganizationNames.slice(0, 2);
                    assignOrganizationNames.push("...");
                }
                return <Space wrap size="small">
                    {assignOrganizationNames.map((item) => {
                        return <Tag key={item}> {item}</Tag>;
                    })}
                </Space>

            },
        },
        // {
        //     title: '采访地点',
        //     hideInSearch: true,
        //     dataIndex: 'address',
        //     formItemProps: {
        //         rules: [
        //             {
        //                 required: true,
        //                 message: '此项为必填项',
        //             },
        //         ],
        //     },
        //     render: (dom, record, _index, action) => {
        //         if (Array.isArray(record?.address)) {
        //             let address = record?.address;

        //             if (address.length > 3) {
        //                 address = address.slice(0, 3);
        //                 address.push("...");
        //             }
        //             return <Space wrap size="small">
        //                 {address.map((item) => {
        //                     return <Tag key={item}> {item}</Tag>;
        //                 })}
        //             </Space>
        //         }
        //     },
        // },
        {
            title: '创建时间',
            key: 'createdTime',
            dataIndex: 'createdTime',
            valueType: 'date',
            sorter: true,
            hideInSearch: true,
            width: 180,
        },
        {
            title: '操作',
            valueType: 'option',
            width: '120px',
            fixed: 'right',
            hideInTable: !access.采访要素匹配x管理员,
            render: (_, row, index, action) => [

                access.采访要素匹配x管理员 && <a
                    key="a_reset_bind_wechat"
                    onClick={() => {
                        Modal.confirm({
                            title: '是否要删除该条活动',
                            icon: <ExclamationCircleOutlined />,
                            okText: '是',
                            okType: 'danger',
                            cancelText: '否',
                            async onOk() {
                                try {
                                    const response = await deleteInterview({ id: row.id });
                                    if (response.code === 0) {
                                        message.success('删除成功');
                                        action?.reload()
                                    }
                                } catch (error) {
                                    message.success('删除失败');
                                    action?.reload()
                                }
                            },
                            onCancel() { },
                        });
                    }}
                >
                    删除
                </a>,
            ],
        },
    ];

    const [totalData, setTotalData] = useState<InterviewRecordData.Statistics>({} as InterviewRecordData.Statistics)

    const getTotal = async () => {
        const res = await getStatisticsRecord({ type })
        console.log(res);
        if (res.code === 0) {
            setTotalData(res.data)
        }
    }
    useEffect(() => {
        getTotal()
        actionRef.current?.reload()
    }, [type])



    useEffect(() => {
        const { interviewId } = parse(location.search) as { interviewId: string };
        console.log(interviewId);
        setInterviewId(interviewId);
    }, [])


    const handleReload = () => {
        getTotal()
        actionRef.current?.reload();
    }
    return (
        <div>
            <Flex wrap gap="small" justify={'space-around'} align={'center'} style={{ marginTop: 10 }}>
                <div>
                    <span style={{ marginRight: 30, fontWeight: 'bold', fontSize: '20px' }}>活动总量</span>
                    <Progress type="dashboard" percent={totalData.total} format={(percent) => `${percent}`} size={[150, 50]} strokeColor="#1677ff" strokeWidth={10} />
                </div>
                <div>
                    <span style={{ marginRight: 30, fontWeight: 'bold', fontSize: '20px' }}>进行中</span>
                    <Progress type="dashboard" percent={totalData.countProgress} size={[150, 50]} format={(percent) => `${percent}`} strokeColor="#52C41A" strokeWidth={10} />
                </div>
                <div>
                    <span style={{ marginRight: 30, fontWeight: 'bold', fontSize: '20px' }}>已结束</span>
                    <Progress type="dashboard" percent={totalData.countComplete} size={[150, 50]} format={(percent) => `${percent}`} strokeColor="#FF5500" strokeWidth={10} />
                </div>
            </Flex>
            <ProTable<InterviewRecordData.PageVo>
                columns={columns}
                actionRef={actionRef}
                style={{ marginTop: 20 }}
                request={async (params, sort, filter) => {

                    const response = await pageInterview({
                        ...params,
                        type
                    });
                    return Promise.resolve({
                        data: response.data.data,
                        total: response.data.total,
                        success: response.code === 0,
                    });
                }}
                editable={{
                    type: 'multiple',
                }}
                columnsState={{
                    persistenceKey: 'pro-table-singe-demos',
                    persistenceType: 'localStorage',
                    defaultValue: {
                        option: { fixed: 'right', disable: true },
                    },
                    onChange(value) {
                        console.log('value: ', value);
                    },
                }}
                rowKey="id"
                search={{
                    labelWidth: 'auto',
                }}
                options={{
                    setting: {
                        listsHeight: 400,
                    },
                }}
                pagination={{
                    pageSize: 20,
                }}
                dateFormatter="string"
                // headerTitle="高级表格"
                toolBarRender={
                    () => (access.采访要素匹配x管理员 || access.采访要素匹配x采访媒体) && <AddInterview onRefurbish={handleReload} />
                }
            />
        </div>
    );
}
export default TableInterview;